package com.coldworks.base.manager;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.coldworks.base.util.BaseCONST;

import android.content.Context;
import android.os.Environment;
import android.os.StatFs;

public class BaseStorageManager {
	protected final Logger log = LoggerFactory.getLogger(this.getClass());
	private static BaseStorageManager instance = null;

	public static BaseStorageManager getInstance() {
		if (instance == null) {
			synchronized (BaseStorageManager.class) {
				if (instance == null) {
					instance = new BaseStorageManager();
				}
			}
		}
		return instance;
	}

	private BaseStorageManager() {
		try {
			List<String> dirs = new ArrayList<String>();
			String sdRoot = getSdRoot();
			if (sdRoot != null) {
				dirs.add(sdRoot + BaseCONST.DIR.ROOT);
				dirs.add(sdRoot + BaseCONST.DIR.BACKUP);
				dirs.add(sdRoot + BaseCONST.DIR.DATA);
				dirs.add(sdRoot + BaseCONST.DIR.SAVE);
				dirs.add(sdRoot + BaseCONST.DIR.SPLASH);
				dirs.add(sdRoot + BaseCONST.DIR.TEMP);
				dirs.add(sdRoot + BaseCONST.DIR.ICON);
				dirs.add(sdRoot + BaseCONST.DIR.IMG);
				dirs.add(sdRoot + BaseCONST.DIR.TOPIC);
				for (String dir : dirs) {
					File tmp = new File(dir);
					if (!tmp.exists()) {
						tmp.mkdir();
					}
				}
			}
			List<String> paths = new ArrayList<String>();
			paths.add(sdRoot + BaseCONST.FILE.LOG);
			for (String path : paths) {
				File file = new File(path);
				if (!file.exists()) {
					file.createNewFile();
				}
			}
		} catch (Exception e) {
			log.error("",e);
		}
	}

	public void clear(Context context) {
		File rootDirectory = getRootDir();
		File backupDir = getBackupDir();
		File dataDir = getDataDir();

		if (rootDirectory == null || backupDir == null || dataDir == null) {
			log.warn("no sdcard");
			return;
		}

		File[] files = rootDirectory.listFiles();

		for (File f : files) {
			String fname = f.getName();
			if (backupDir.getName().equals(fname)
					|| dataDir.getName().equals(fname)) {
				continue;
			}

			File backup = new File(backupDir.getAbsolutePath() + File.separator
					+ fname + "_bak");

			if (f.isDirectory()) {
				if (!backup.exists()) {
					backup.mkdir();
				}
			} else { // f is file
				if (!backup.exists()) {
					try {
						backup.createNewFile();
					} catch (IOException e) {
						log.error("",e);
						continue;
					}
				}
			}

			if (f.renameTo(backup)) {
				log.info("backuped: " + fname);
			} else {
				log.warn("backuped err: " + fname);
			}
		}

		File fileCache = getCacheDir();
		if (fileCache != null) {
			try {
				delAllChild(fileCache); // 删除cache目录里面所有内容
			} catch (Exception e) {
				log.error("",e);
			}
			fileCache.delete();
		}
		log.info("done");
	}

	public void delAllChild(File file) {
		if (!file.exists() || !file.isDirectory()) {
			return;
		}
		File[] files = file.listFiles();
		for (File one : files) {
			if (one.isFile()) {
				one.delete();
			} else if (one.isDirectory()) {
				delAllChild(one);// 先删除文件夹里面的文件
				one.delete();
			}
		}
	}

	/**
	 * 是否挂载SD卡
	 */
	public boolean hasSD() {
		// return false;
		return Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED);
	}

	/**
	 * 取得手机存储剩余空间
	 */
	public long getInternalAvailableStore() {
		return getAvailableStore(Environment.getDataDirectory()
				.getAbsolutePath());
	}

	/**
	 * 取得手机sd卡剩余空间
	 */
	public long getSDAvailableStore() {
		String state = Environment.getExternalStorageState();
		if (Environment.MEDIA_MOUNTED.equals(state)) {
			if (Environment.getExternalStorageDirectory().canWrite()) {
				return getAvailableStore(Environment
						.getExternalStorageDirectory().getPath());
			}
		}
		return -1;
	}

	public long getAvailableStore(String filePath) {
		StatFs statFs = new StatFs(filePath);
		long blocSize = statFs.getBlockSize();
		long availaBlock = statFs.getAvailableBlocks();
		long availableSpare = availaBlock * blocSize;
		return availableSpare;
	}

	/**
	 * SD卡根路径
	 * 
	 * @return
	 */
	public String getSdRoot() {
		if (hasSD()) {
			return Environment.getExternalStorageDirectory().getAbsolutePath();
		}
		return null;
	}

	/**
	 * 安卓壁纸在SD里的根路径 如果该文件(夹)不存在，原因可能是本机没挂在sd卡等原因
	 * 如果该文件(夹)存在，此方法会尝试new一个File，只有当new出的File成功时，才会返回文件 否则一律返回null
	 * 
	 * @return
	 */
	public File getRootDir() {
		String sdRoot = getSdRoot();
		if (sdRoot != null) {
			File file = new File(sdRoot + BaseCONST.DIR.ROOT);
			if (file.exists() && file.isDirectory()) {
				return file;
			}
		}
		return null;
	}

	/**
	 * 本地Data路径
	 * 
	 * @return
	 */
	public File getDataDir() {
		String sdRoot = getSdRoot();
		if (sdRoot != null) {
			File file = new File(sdRoot + BaseCONST.DIR.DATA);
			if (file.exists() && file.isDirectory()) {
				return file;
			}
		}
		return null;
	}

	public File getSaveDir() {
		String sdRoot = getSdRoot();
		if (sdRoot != null) {
			File file = new File(sdRoot + BaseCONST.DIR.SAVE);
			if (file.exists() && file.isDirectory()) {
				return file;
			}
		}
		return null;
	}

	public File getTopicDir() {
		String sdRoot = getSdRoot();
		if (sdRoot != null) {
			File file = new File(sdRoot + BaseCONST.DIR.TOPIC);
			if (file.exists() && file.isDirectory()) {
				return file;
			}
		}
		return null;
	}

	/**
	 * 临时目录路径
	 * 
	 * @return
	 */
	public File getTempDir() {
		String sdRoot = getSdRoot();
		if (sdRoot != null) {
			File file = new File(sdRoot + BaseCONST.DIR.TEMP);
			if (file.exists() && file.isDirectory() && file.canWrite()
					&& file.canRead()) {
				return file;
			}
		}
		return null;
	}

	/**
	 * 欢迎页图片路径
	 * 
	 * @return
	 */
	public File getSplashDir() {
		String sdRoot = getSdRoot();
		if (sdRoot != null) {
			File file = new File(sdRoot + BaseCONST.DIR.SPLASH);
			if (file.exists() && file.isDirectory()) {
				return file;
			}
		}
		return null;
	}

	/**
	 * 非个人收藏壁纸的备份路径
	 * 
	 * @return
	 */
	public File getBackupDir() {
		String sdRoot = getSdRoot();
		if (sdRoot != null) {
			File file = new File(sdRoot + BaseCONST.DIR.BACKUP);
			if (file.exists() && file.isDirectory()) {
				return file;
			}
		}
		return null;
	}

	public File getIconDir() {
		String sdRoot = getSdRoot();
		if (sdRoot != null) {
			File file = new File(sdRoot + BaseCONST.DIR.ICON);
			if (file.exists() && file.isDirectory()) {
				return file;
			}
		}
		return null;
	}

	public File getImgDir() {
		String sdRoot = getSdRoot();
		if (sdRoot != null) {
			File file = new File(sdRoot + BaseCONST.DIR.IMG);
			if (file.exists() && file.isDirectory()) {
				return file;
			}
		}
		return null;
	}

	/**
	 * 本地浏览壁纸时的缓存路径
	 * 
	 * @return
	 */
	public File getCacheDir() {
		String sdRoot = getSdRoot();
		if (sdRoot != null) {
			File file = new File(sdRoot + BaseCONST.DIR.CACHE);
			if (file.exists() && file.isDirectory() && file.canWrite()) {
				return file;
			}
		}
		return null;
	}

	/**
	 * log文件路径
	 * 
	 * @return
	 */
	public File getLogFile() {
		String sdRoot = getSdRoot();
		if (sdRoot != null) {
			File file = new File(sdRoot + BaseCONST.FILE.LOG);
			if (file.exists() && file.isFile() && file.canRead()
					&& file.canWrite()) {
				return file;
			}
		}
		return null;
	}

	/**
	 * err文件路径
	 * 
	 * @return
	 */
	public File getLogErrFile() {
		String sdRoot = getSdRoot();
		if (sdRoot != null) {
			return new File(sdRoot + BaseCONST.FILE.LOG_ERR);
		}
		return null;
	}

	/**
	 * share文件路径
	 * 
	 * @return
	 */
	public File getShareFile() {
		String sdRoot = getSdRoot();
		if (sdRoot != null) {
			return new File(sdRoot + BaseCONST.FILE.SHARE);
		}
		return null;
	}

}
